<!--
 * @Author: xie_sm
 * @Date: 2022-02-28 16:07:02
 * @LastEditors: xie_sm
 * @LastEditTime: 2023-03-14 16:30:04
 * @FilePath: \mobile-template\src\App.vue
 * @Description:
 *
-->
<template>
  <div id="app" ref="app">
    <transition name="fade">
      <keep-alive>
        <router-view v-if="$route.meta.keepAlive" class="router"></router-view>
      </keep-alive>
    </transition>
    <transition name="fade">
      <router-view v-if="!$route.meta.keepAlive" class="router"></router-view>
    </transition>
  </div>
</template>
<script>
/* eslint-disable no-undef */
// 该组件需要和真机交互，会出现原生 API 未定义的情况，故全局应用屏蔽 no-undef 规则
import { loadLanguageAsync, getLangConfig } from '@/utils/locale/index' //引入获取系统语言的方法
import { Toast } from 'fawkes-mobile-lib'
import { clickOther, scroll, getScrollTop, getScrollHeight, getWindowHeight } from '@/utils/monitor'
import { LANG_FROM_KEY } from '@/common/constant'
import { SET_STATUS_BAR_HEIGHT } from '@/store/Mutation/mutationTypes'
import { mapGetters } from 'vuex'

export default {
  components: {
    [Toast.name]: Toast,
  },
  data() {
    return {
      statusBarHeight: null,
      needUpdate: true,
    }
  },
  computed: {
    ...mapGetters(['isLogin']),
  },
  watch: {
    $route(to) {
      if (typeof yuanchu != 'undefined') {
        yuanchu?.statusBar?.getStatusBarHeight((res) => {
          this.$store.commit(SET_STATUS_BAR_HEIGHT, res)
          if (to.path == '/home') {
            yuanchu.statusBar.styleLightContent()
          } else {
            yuanchu.statusBar.styleDefault()
            this.$refs.app.style.setProperty('--height', res + 'px')
          }
        })
      }
    },
  },
  created() {
    this.onLoad()
  },
  mounted() {
    window.addEventListener('click', clickOther, true)
    window.addEventListener('scroll', this.triggerScrol, true)

    // 获取手机系统语言，同步切换语言
    const language = getLangConfig()
    // TODO: 考虑是否有必要存储在localstorage，后期优化调整点
    this.$storage.set('i18nLocale', language)
    console.log(language)
    this.$i18n.locale = language
    LANG_FROM_KEY.map((item) => {
      if (item.key == this.$i18n.locale) {
        this.$i18n.locale = item.key
        this.$storage.set('i18nLocaleKey', item.locale)
        loadLanguageAsync(item.key, item.locale, this)
      }
    })
    //处理ios手势滑动操作
    if (typeof yuanchu !== 'undefined') {
      yuanchu.device.getInfo((res) => {
        if (res.platform.toUpperCase() === 'IOS') {
          let startX = null // 触摸开始X轴位置
          let startY = null
          let endX = null // 触摸结束X轴位置
          let endY = null
          let moveX = null // 触摸移动X轴距离
          let moveY = null

          let isExit = false //下一次是否退出应用

          document.addEventListener('touchstart', (e) => {
            startX = e.touches[0].screenX
            startY = e.touches[0].screenY
          })

          document.addEventListener('touchend', (e) => {
            endX = e.changedTouches[0].screenX
            endY = e.changedTouches[0].screenY
            moveX = startX - endX
            moveY = startY - endY

            if (startX < 20 && Math.abs(moveX) > 15 && Math.abs(moveY) < 20) {
              const pathList = ['/home', '/deviceDetail', '/personalCenter']

              if (moveX < 0) {
                //边缘右滑
                if (pathList.includes(this.$route.path)) {
                  if (isExit) {
                    isExit = false
                    navigator.app.exitApp()
                    return
                  }

                  isExit = true

                  Toast({
                    message: '三秒内再点一次退出应用！',
                    forbidClick: true,
                    duration: 1000,
                  })

                  let inter = setInterval(() => {
                    clearInterval(inter)
                    isExit = false
                  }, 3000)
                } else {
                  this.$router.go(-1)
                }
              } else {
                //边缘左滑
              }
            }
          })
        }
      })
    }
  },
  beforeDestroy() {
    window.removeEventListener('storage', function () {})
  },
  methods: {
    // 页面加载后添加各事件监听
    onLoad() {
      document.addEventListener('deviceready', this.onDeviceReady, false)
    },
    // Cordova加载完毕
    onDeviceReady() {
      if (typeof yuanchu != 'undefined') {
        yuanchu.statusBar.styleDefault()
      }
      //判断是否需要热更新
      document.addEventListener('chcp_nothingToUpdate', this.nothingToUpdate, false)
      //有些项目不需要热更新
      // if (this.needUpdate) {
      //   this.$loading.show({ title: '检查更新中' })
      //   yuanchu.chcp.fetchUpdate(this.fetchUpdateCallback)
      // }
      // main.js中定义$back
      document.addEventListener('backbutton', this.$back, false) // 默认返回上一级路由，其他情况自行处理
      // 推送
      this.JPushInit()
    },
    JPushInit() {
      document.addEventListener(
        'jpush.receiveRegistrationId',
        function (event) {
          console.log(JSON.stringify(event))
          alert('receiveRegistrationId: ' + JSON.stringify(event))
        },
        false
      )
      document.addEventListener('jpush.openNotification', this.onOpenNotification, false)
      document.addEventListener('jpush.receiveNotification', this.onReceiveNotification, false)
      document.addEventListener('jpush.receiveMessage', this.onReceiveMessage, false)

      try {
        window.JPush.init()
        window.JPush.setDebugMode(true)
        window.setTimeout(this.getRegistrationID, 1000)

        if (yuanchu.device.platform != 'Android') {
          window.JPush.setApplicationIconBadgeNumber(0)
        }
      } catch (exception) {
        console.log(exception)
      }
    },
    onOpenNotification(event) {
      try {
        var alertContent
        if (yuanchu.device.platform == 'Android') {
          alertContent = event.alert
        } else {
          alertContent = event.aps.alert
        }

        badgeNumb = badgeNumb - 1
        badgeNumb = badgeNumb <= 0 ? 0 : badgeNumb
        window.JPush.setBadgeNumber(badgeNumb)

        alert('用户点击消息通知: ' + alertContent)
      } catch (exception) {
        console.log('JPushPlugin:onOpenNotification' + exception)
      }
    },
    onReceiveNotification(event) {
      try {
        var alertContent
        if (yuanchu.device.platform == 'Android') {
          alertContent = event.alert
        } else {
          alertContent = event.aps.alert
        }

        console.log('notificationResult： ' + alertContent)
        alert('接受到消息通知: ' + alertContent)

        badgeNumb = badgeNumb + 1
        window.JPush.setBadgeNumber(badgeNumb)
      } catch (exception) {
        console.log(exception)
      }
    },
    onReceiveMessage(event) {
      try {
        var message
        if (yuanchu.device.platform == 'Android') {
          message = event.message
        } else {
          message = event.content
        }

        console.log('messageResult： ' + message)
        alert('接受到消息: ' + message)

        badgeNumb = badgeNumb + 1
        window.JPush.setBadgeNumber(badgeNumb)
      } catch (exception) {
        console.log('JPushPlugin:onReceiveMessage-->' + exception)
      }
    },
    getRegistrationID() {
      window.JPush.getRegistrationID(this.onGetRegistrationID)
    },
    onGetRegistrationID(data) {
      try {
        console.log('JPushPlugin:registrationID is ' + data)

        if (data.length == 0) {
          var t1 = window.setTimeout(getRegistrationID, 1000)
        }

        console.log('registrationID: ' + data)
        alert('registrationID: ' + data)
      } catch (exception) {
        console.log(exception)
      }
    },
    //无热更新
    nothingToUpdate() {
      this.needUpdate = false
    },
    fetchUpdateCallback(error, data) {
      if (error) {
        //没更新
        this.$loading.hide()
        console.log('data', JSON.stringify(data))
        if (error.code == 2) {
        } else if (error.code == -2) {
          Toast('您的App版本过低，请升级')
          //您的App原生框架版本过低，请升级
        } else {
          //根据error.code对获取更新结果做提示用户、重新调用更新检查方法等其他额外处理
        }
      } else {
        //检查更新正常，开始安装更新
        yuanchu.chcp.installUpdate(this.installationCallback)
      }
    },
    installationCallback(error) {
      if (error) {
        this.$loading.hide()
        //根据error.code对安装更新异常做提示用户、重新调用安装更新方法等其他额外处理
      } else {
        Toast('热更新完成')
        this.$loading.hide()
      }
    },
    triggerScrol() {
      if (Math.round(getScrollTop() + getWindowHeight()) == getScrollHeight()) {
        scroll()
      }
    },
  },
}
</script>
<style lang="less" scoped>
#app {
  font-size: 16px;
  height: calc(100vh - constant(safe-area-inset-bottom));
  height: calc(100vh - env(safe-area-inset-bottom));
  background-color: #fff;
  overflow: hidden;
  width: 100%;
  //ios底部适配

  padding-bottom: constant(safe-area-inset-bottom); //兼容 IOS<11.2

  padding-bottom: env(safe-area-inset-bottom); //兼容 IOS>11.2
}
/deep/.fm-nav-bar {
  padding-top: var(--height);
}
/deep/.fm-list__finished-text {
  padding-bottom: var(--height);
}
/deep/.fm-tab--active {
  color: #4545d1;
}
/deep/.fm-tabs__line {
  background-color: #4545d1;
}
/deep/.fm-sidebar-item--select::before {
  background-color: #4545d1;
}
</style>
